package com.haobao.telephonerecord

import android.Manifest
import android.R.attr
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import android.os.Environment
import com.haobao.telephonerecord.utils.FileUtils
import com.haobao.telephonerecord.utils.TimeUtils
import java.io.File
import android.telecom.PhoneAccountHandle

class MainActivity : AppCompatActivity() {
    lateinit var etPhone: EditText
    lateinit var btnCall: Button
    lateinit var mRecyclerView: RecyclerView
    lateinit var mRecordAdapter: RecordAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        EventBus.getDefault().register(this)
        etPhone = findViewById(R.id.etPhone)
        btnCall = findViewById(R.id.btnCall)
        mRecyclerView = findViewById(R.id.mRecyclerView)
        //etPhone.setText("18865526389")

        getPermission()
        initAdapter();
        phoneListener();

        //  getLocalAudioList()


        btnCall.setOnClickListener {
            val strPhone = etPhone.text.toString().trim()
            if (!TextUtils.isEmpty(strPhone)) {
                callPhone(strPhone);
                /*if (strPhone.length == 11) {

                } else {
                    Toast.makeText(this, "手机号格式不对", Toast.LENGTH_SHORT).show();
                }*/
            } else {
                Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            }
        }
    }

    val mList: MutableList<Song> = ArrayList();
    private fun initAdapter() {
        mRecordAdapter = RecordAdapter(this, mList);
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.adapter = mRecordAdapter
    }

    private val tag = "PhoneListenService"

    // 电话管理者对象
    private var mTelephonyManager: TelephonyManager? = null

    // 电话状态监听者
    private var myPhoneStateListener: MyPhoneStateListener? = null

    // 动态监听去电的广播接收器
    //private var mInnerOutCallReceiver: InnerOutCallReceiver? = null
    private fun phoneListener() {
        mTelephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        myPhoneStateListener = MyPhoneStateListener()
        mTelephonyManager!!.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)

        // 动态注册广播接收器监听去电信息
        //mInnerOutCallReceiver = InnerOutCallReceiver()
        // 手机拨打电话时会发送：android.intent.action.NEW_OUTGOING_CALL的广播
        //val intentFilter = IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL)
        //registerReceiver(mInnerOutCallReceiver, intentFilter)

        FileUtils.deleteNoMediaFiles();

    }

    /**
     * 获取本地音频文件
     */
    public fun getLocalAudioList() {


        //MediaStore.Audio.AudioColumns.IS_MUSIC
        //MediaStore.Audio.AudioColumns.IS_MUSIC
        //  MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        //val path1 = Environment.getExternalStorageDirectory().toString()
        //println("MainActivity.onCreate path1="+path1)

        val cursor = contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            "${MediaStore.Audio.AudioColumns.DATE_ADDED} desc"
        )
        if (cursor != null) {
            mList.clear()
            while (cursor.moveToNext()) {
                val song =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                val singer =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                val path =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                val duration =
                    cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                val size =
                    cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));

                val date_taken =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_TAKEN));

                val date_modified =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_MODIFIED));

                val date_add =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_ADDED));

                println(
                    "getLocalAudioList song=$song " +
                            "singer=$singer " +
                            "path=$path " +
                            "duration=$duration " +
                            "date_add=$date_add " +
                            "date_modified=${TimeUtils.getDateToString(date_modified.toLong())} " +
                            "date_taken=$date_taken " +
                            "size=$size "
                )
                val mSong = Song()
                mSong.song = song;
                mSong.path = path;
                mSong.date = date_add
                mSong.duration = duration;
                mList.add(mSong)

            }
            cursor.close()
        } else {
            println("MainActivity.getLocalAudioList else")
        }
        mRecordAdapter.notifyDataSetChanged()

    }


    public fun getLocalAudioList1() {
//MediaStore.Audio.AudioColumns.IS_MUSIC
        val cursor = contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            "${MediaStore.Audio.AudioColumns.DATE_ADDED} desc"
        )
        if (cursor != null) {
            mList.clear()

            cursor.moveToFirst()
            val song =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
            val singer =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
            val path =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            val duration =
                cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
            val size =
                cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));

            val date_modified =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_MODIFIED));

            val date_add =
                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_ADDED));

            println(
                "getLocalAudioList song=$song " +
                        "singer=$singer " +
                        "path=$path " +
                        "duration=$duration " +
                        "size=$size "
            )
            val mSong = Song()
            mSong.song = song;
            mSong.path = path;
            mSong.date = date_add
            mList.add(mSong)


            cursor.close()
        }
        mRecordAdapter.notifyDataSetChanged()

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun messageEvent(mEvent: EventResult) {
        Handler(Looper.getMainLooper()).postDelayed(Runnable { getLocalAudioList() }, 1000)
    }

    /**
     * 动态注册广播接收器监听去电信息
     */
    /*internal class InnerOutCallReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            // 获取播出的去电号码
            val outPhone = resultData
            Log.i("ypk", "outPhone:$outPhone")
        }
    }*/


    /**
     * 自定义内部类对来电的电话状态进行监听
     */
    internal class MyPhoneStateListener : PhoneStateListener() {
        // 重写电话状态改变时触发的方法
        override fun onCallStateChanged(state: Int, incomingNumber: String) {
            super.onCallStateChanged(state, incomingNumber)
            when (state) {
                TelephonyManager.CALL_STATE_RINGING -> {
                    Log.i("ypk", "响铃:$incomingNumber")

                }
                TelephonyManager.CALL_STATE_OFFHOOK -> {
                    Log.i("ypk", "接听")

                }
                TelephonyManager.CALL_STATE_IDLE -> {
                    Log.i("ypk", "挂断")
                    //FileUtils.deleteNoMediaFiles();
                    //开始扫描本地音频文件
                    EventBus.getDefault().post(EventResult())
                }
            }
        }
    }


    /**
     * 截图
     * 拨打电话（直接拨打电话）
     * @param phoneNum 电话号码
     */
    fun callPhone(phoneNum: String) {
        val intent = Intent(Intent.ACTION_CALL)
        val data: Uri = Uri.parse("tel:$phoneNum")

       // val phoneAccountHandle: PhoneAccountHandle = getPhoneAccountHandle(slotId)
        intent.data = data
        startActivity(intent)

        //val intent = Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION)
        //startActivityForResult(intent, REQUEST_RECORDER)
    }

    private val REQUEST_RECORDER = 0x000001
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && REQUEST_RECORDER == requestCode) {
            val uri: Uri? = data?.data
            if (uri != null) {
                println("MainActivity.onActivityResult uri is ")
            }
        }
    }

    val permissions = arrayOf(
        Manifest.permission.CALL_PHONE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.RECORD_AUDIO
    )

    private fun getPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            val callPhone = ContextCompat.checkSelfPermission(this, permissions[0])
            if (callPhone != PackageManager.PERMISSION_GRANTED) {
                println("MainActivity.getPermission 没有callPhone权限")
                ActivityCompat.requestPermissions(this, permissions, 300)
            } else {
                println("MainActivity.getPermission 已有callPhone权限")
            }

            val write = ContextCompat.checkSelfPermission(this, permissions[1])
            if (write != PackageManager.PERMISSION_GRANTED) {
                println("MainActivity.getPermission 没有write权限")
                ActivityCompat.requestPermissions(this, permissions, 301)
            } else {
                println("MainActivity.getPermission 已有write权限")
            }

            val read = ContextCompat.checkSelfPermission(this, permissions[2])
            if (read != PackageManager.PERMISSION_GRANTED) {
                println("MainActivity.getPermission 没有read权限")
                ActivityCompat.requestPermissions(this, permissions, 302)
            } else {
                println("MainActivity.getPermission 已有read权限")
            }

            val record_audio = ContextCompat.checkSelfPermission(this, permissions[3])
            if (record_audio != PackageManager.PERMISSION_GRANTED) {
                println("MainActivity.getPermission 没有 record_audio 权限")
                ActivityCompat.requestPermissions(this, permissions, 303)
            } else {
                println("MainActivity.getPermission 已有 record_audio 权限")
            }
        }

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {

        } else {
            Toast.makeText(this, " 获取权限成功", Toast.LENGTH_SHORT).show();
            println("MainActivity.onRequestPermissionsResult 获取权限成功")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

}